<?php

class BlockController extends Controller
{


    /**
     * Displays a particular model.
     * @param integer $id the ID of the model to be displayed
     */
    public function actionView($id)
    {
        $this->render('view',array(
                'model'=>$this->loadModel($id),
        ));
    }

    /**
     * Creates a new model.
     * If creation is successful, the browser will be redirected to the 'view' page.
     */
    public function actionCreate()
    {
        $block=new Block;
        $address=new Address;

        // $this->performAjaxValidation($block);

        if(isset($_POST['Address']) && isset($_POST['Block']))
        {
            $address->attributes=$_POST['Address'];
            $block->attributes=$_POST['Block'];

            if(!checkAccess('admin')){
                $block->user_id = user()->id;
            }

            $block->validate();

            if($address->save()){
                $block->address_id = $address->id;

                if($block->save())
                    $this->redirect(array('view','id'=>$block->id));
            }
        }

        $this->render('create',array(
                'model'=>$block,
                'address'=>$address,
        ));
    }

    /**
     * Updates a particular model.
     * If update is successful, the browser will be redirected to the 'view' page.
     * @param integer $id the ID of the model to be updated
     */
    public function actionUpdate($id)
    {
        $model=$this->loadModel($id);

        $this->accessDeniedIf(!checkAccess('ownBlock', array('block'=>$model)), 'Nincs joga ehhez a háztömbhöz.');

        $address=Address::model()->findByPk($model->address_id);

        // $this->performAjaxValidation($model);

        if(isset($_POST['Block']) || isset($_POST['Address']))
        {

            $address->attributes=$_POST['Address'];
            $address->save();

            $model->attributes=$_POST['Block'];
            if($model->save())
                $this->redirect(array('view','id'=>$model->id));
        }

        // block flat categories
        $flatCategory = new FlatCategory('search');
        $flatCategory->unsetAttributes();  // clear any default values

        $flatCategory = $flatCategory->byBlock($model);

        if(isset($_GET['FlatCategory'])){
            $flatCategory->attributes = $_GET['FlatCategory'];
        }

        // block providers
        $provider = new Provider('search');
        $provider->unsetAttributes();  // clear any default values

        $provider = $provider->byUser($model->user);

        if(isset($_GET['Provider'])){
            $provider->attributes = $_GET['Provider'];
        }

        $this->render('update',array(
                'model'=>$model,
                'address'=>$address,
                'flatCategory'=>$flatCategory,
                'provider'=>$provider
        ));
    }

    /**
     * Deletes a particular model.
     * If deletion is successful, the browser will be redirected to the 'admin' page.
     * @param integer $id the ID of the model to be deleted
     */
    public function actionDelete($id)
    {
        $transaction= webapp()->db->beginTransaction();
        try {
            $model = $this->loadModel($id);
            $model->address->delete();
            $model->delete();

            $transaction->commit();

        } catch(Exception $e) {
            Yii::log('Adatbázis hiba \n' . $e->getMessage(), 'error', 'anett.block');
            $transaction->rollback();

            echo CJSON::encode(array('type'=>'error', 'message'=> $e->getMessage()));

            Yii::app()->end();
        }

        if(!isset($_GET['ajax']))
            $this->redirect(isset($_POST['returnUrl']) ? $_POST['returnUrl'] : array('index'));

    }

    /**
     * Lists all models.
     */
    public function actionIndex()
    {
        $model=new Block('search');
        $model->unsetAttributes();  // clear any default values
        if(isset($_GET['Block'])){
            $model->attributes=$_GET['Block'];
            $model->addressSearch=$_GET['Block']['addressSearch'];
            $model->userSearch=$_GET['Block']['userSearch'];
        }

        // admin see all block
        if(!checkAccess('admin'))
            $model = $model->owned(user());

        $this->render('index',array(
                'model'=>$model,
        ));
    }



    /**
     * Returns the data model based on the primary key given in the GET variable.
     * If the data model is not found, an HTTP exception will be raised.
     * @param integer the ID of the model to be loaded
     */
    public function loadModel($id)
    {
        $model=Block::model()->findByPk($id);
        if($model===null)
            throw new CHttpException(404,'The requested page does not exist.');
        return $model;
    }

    /**
     * Performs the AJAX validation.
     * @param CModel the model to be validated
     */
    protected function performAjaxValidation($model)
    {
        if(isset($_POST['ajax']) && $_POST['ajax']==='block-form')
        {
            echo CActiveForm::validate($model);
            Yii::app()->end();
        }
    }
}
